package org.apache.cassandra.server.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.cassandra.server.CassandraNodeActivator;
import org.apache.cassandra.server.INodeConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import fr.aliasource.utils.DOMUtils;
import fr.aliasource.utils.FileUtils;

/**
 * Creates Cassandra configuration suitable for a bigg node
 * 
 * @author tom
 *
 */
public class ConfWriter {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private String storePath;
	private String logPath;

	/**
	 * Create the configuration in the given directory
	 * 
	 * @param confDir
	 */
	public ConfWriter(File confDir) {
		storePath = confDir.getAbsolutePath() + "/storage-conf.xml";
		logPath = confDir.getAbsolutePath() + "/log4j.properties";
	}

	/**
	 * Writes the configuration to disk
	 * 
	 * @param conf
	 */
	public void write(INodeConfiguration conf) {
		logger.info("writing configuration to " + storePath + "...");

		// create storage-conf.xml
		InputStream in = CassandraNodeActivator.class.getClassLoader()
				.getResourceAsStream("templates/storage-conf.xml");
		Document doc = null;
		try {
			doc = DOMUtils.parse(in);
			mergeData(doc, conf);
			FileOutputStream out = new FileOutputStream(storePath);
			DOMUtils.serialise(doc, out);
		} catch (Throwable t) {
			logger.error(t.getMessage(), t);
		}

		// create log4j conf
		logger.info("writing configuration to " + logPath + "...");
		in = CassandraNodeActivator.class.getClassLoader().getResourceAsStream(
				"log4j.properties");
		try {
			FileOutputStream out = new FileOutputStream(logPath);
			FileUtils.transfer(in, out, true);
		} catch (Throwable t) {
			logger.error(t.getMessage(), t);
		}

		logger.info("configuration created.");
	}

	private void mergeData(Document doc, INodeConfiguration conf) {
		logger.info("TODO merge provided conf into storage-conf.xml template");
	}

}
